package com.bobbygu.libnet.common;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * EncryptionConverterFactory
 * 加密转换工厂类，http请求发出前对数据进行加密，收到请求结果后，对结果进行解密
 * <p>
 * author: 顾博君 <br>
 * time:   2017/8/17 15:33 <br>
 * e-mail: gubojun@csii.com.cn <br>
 * </p>
 */

public class EncryptionConverterFactory extends Converter.Factory {
    private final Gson gson;

    public static EncryptionConverterFactory create(Gson gson) {
        return new EncryptionConverterFactory(gson);
    }

    private EncryptionConverterFactory(Gson gson) {
        this.gson = gson;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type,
                                                            Annotation[] annotations,
                                                            Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new EncryptionResponseConverter<>(type, gson, adapter, true);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations,
                                                          Annotation[] methodAnnotations,
                                                          Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new EncryptionRequestConverter<>(gson, adapter, true);
    }
}
